package com.cloudcc.cloudframe.net.async;

import com.cloudcc.cloudframe.bus.IDataEvent;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ServerStatusCode;
import com.cloudcc.cloudframe.util.NumberUtils;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import de.greenrobot.event.EventBus;

/**
 * Created by lin on 2017/7/21.
 *
 * 天眼查专供request
 */

public class TianYanChaRequest extends TextHttpResponseHandler implements
        ServerStatusCode {

    protected IDataEvent<String> mEvent;

    public void setEvent(IDataEvent<String> event) {
        this.mEvent = event;
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String s, Throwable throwable) {

        ErrorInfo e;
        if (statusCode == NET_INTERCEPTOR) {
            int errorCode = NumberUtils.toInt(throwable.getMessage(), -100);
            if (errorCode != -100) {
                e = ErrorInfo.get(errorCode);
            } else {
                e = new ErrorInfo(NET_DATA_EXCEPTION);
            }
        } else {
            e = new ErrorInfo(NET_DATA_EXCEPTION);
        }

        if (mEvent != null) {
            mEvent.setOk(false);
            mEvent.setMessage(e.getErrorMessage());
            EventBus.getDefault().post(mEvent);
        }
    }

    @Override
    public void onSuccess(int i, Header[] headers, String s) {


        if (mEvent != null) {
            mEvent.setData(s);
            mEvent.setOk(true);
            EventBus.getDefault().post(mEvent);
        }
    }
}
